package jvm.ref;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.TimeUnit;

/**
 * 虚引用
 * @author jiangwz
 * @create 2019/9/17.
 */
public class PhantomReferenceDemo {

    public static void main(String[] args){
        Object o1 = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        PhantomReference<Object> phantomReference = new PhantomReference<>(o1, referenceQueue);

        // GC之前
        System.out.println(o1);
        System.out.println(phantomReference.get()); //永远获取不到
        System.out.println(referenceQueue.poll());

        System.out.println("===========");

        o1 = null;
        System.gc();
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        // GC之后
        System.out.println(o1);
        System.out.println(phantomReference.get());//永远获取不到
        System.out.println(referenceQueue.poll()); //但是GC后队列里面能获取到


    }

}
